package han.util;


/**
 * 类描述：smartQQ工具类
 *
 * @author: hugan
 * @amend: han
 * @date: 2017-5-3 下午03:45:53
 */
public class QqUtils {

    private static long t;

    static {
        t = (t - t % 1000L) / 1000L;
        t = t % 10000L * 10000L;
    }

    /**
     * 方法描述：得到hash
     *
     * @param uin       uin
     * @param ptvfwebqq ptvfwebqq
     * @return String
     * @author: hugan
     * @date: 2017-5-3 下午03:46:46
     */
    public static String hash(long uin, String ptvfwebqq) {
        int[] ptb = new int[4];
        for (int i = 0; i < ptvfwebqq.length(); i++) {
            int ptbIndex = i % 4;
            ptb[ptbIndex] ^= ptvfwebqq.charAt(i);
        }
        String[] salt = {"EC", "OK"};
        long[] uinByte = new long[4];
        uinByte[0] = (((uin >> 24) & 0xFF) ^ salt[0].charAt(0));
        uinByte[1] = (((uin >> 16) & 0xFF) ^ salt[0].charAt(1));
        uinByte[2] = (((uin >> 8) & 0xFF) ^ salt[1].charAt(0));
        uinByte[3] = ((uin & 0xFF) ^ salt[1].charAt(1));
        long[] result = new long[8];
        for (int i = 0; i < result.length; i++) {
            if (i % 2 == 0) {
                result[i] = ptb[i >> 1];
            } else {
                result[i] = uinByte[i >> 1];
            }
        }
        return byteTohex(result);
    }

    private static String byteTohex(long[] result) {
        char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        StringBuilder buf = new StringBuilder();

        for (long aResult : result) {
            buf.append(hex[new Long((aResult >> 4) & 0xF).intValue()]);
            buf.append(hex[new Long(aResult & 0xF).intValue()]);
        }
        return buf.toString();
    }

    public static int hash3(String qrsig) {
        int e = 0;
        for (int i = 0, n = qrsig.length(); n > i; ++i) {
            e += (e << 5) + qrsig.charAt(i);
        }
        return 2147483647 & e;
    }

    /**
     * QQ群官网的bkn参数
     *
     * @param skey cookie中的skey
     * @return bkn
     */
    public static int bkn(String skey) {
        int t = 5381;
        for (int i = 0; i < skey.length(); ++i) {
            t += (t << 5) + skey.charAt(i);
        }
        return 2147483647 & t;
    }
}
